package com.example.service.other;

import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ObjectUtil;
import com.example.common.Constants;
import com.example.common.enums.ResultCodeEnum;
import com.example.common.enums.RoleEnum;
import com.example.common.enums.RoleStatusEnum;
import com.example.exception.CustomException;
import com.example.mapper.shopping.BusinessMapper;
import com.example.mapper.shopping.MedicinesMapper;
import com.example.model.dto.AccountDto;
import com.example.model.entity.medical.Doctor;
import com.example.model.entity.other.Account;
import com.example.model.entity.shopping.Business;
import com.example.model.entity.shopping.Medicines;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商家信息表业务处理
 **/
@Service
public class BusinessService {

    @Resource
    private BusinessMapper businessMapper;
    @Resource
    private MedicinesMapper medicinesMapper;

    /**
     * 新增
     */
    public void add(Business business) {
        Business dbBusiness = businessMapper.selectByUsername(business.getUsername());
        if (ObjectUtil.isNotNull(dbBusiness)) {
            throw new CustomException(ResultCodeEnum.USER_EXIST_ERROR);
        }
        Account currentUser = TokenUtils.getCurrentUser();
        if(RoleEnum.ADMIN.name().equals(currentUser.getRole())){
            if (ObjectUtil.isEmpty(business.getPassword())) {
                business.setPassword(Constants.BUSINESS_DEFAULT_PASSWORD);
            }
            business.setRole(RoleEnum.BUSINESS.name());
            business.setStatus(RoleStatusEnum.STATUS_OK.getName());
            businessMapper.insert(business);
        }

    }

    /**
     * 删除
     */
    public void deleteById(Integer id) {
        businessMapper.deleteById(id);
    }

    /**
     * 批量删除
     */
    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            businessMapper.deleteById(id);
        }
    }

    /**
     * 修改
     */
    public void updateById(Business business) {
        businessMapper.updateById(business);
    }

    /**
     * 根据ID查询
     */
    public Business selectById(Integer id) {
        return businessMapper.selectById(id);
    }

    /**
     * 查询所有
     */
    public List<Business> selectAll(Business business) {
        return businessMapper.selectAll(business);
    }

    /**
     * 分页查询
     */
    public PageInfo<Business> selectPage(Business business, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Business> list = businessMapper.selectAll(business);
        return PageInfo.of(list);
    }

    /**
     * 登录
     */
    public Account login(AccountDto accountDto) {
        Account dbBusiness = businessMapper.selectByUsername(accountDto.getUsername());
        if (ObjectUtil.isNull(dbBusiness)) {
            throw new CustomException(ResultCodeEnum.USER_NOT_EXIST_ERROR);
        }
        if (!accountDto.getPassword().equals(dbBusiness.getPassword())) {
            throw new CustomException(ResultCodeEnum.USER_ACCOUNT_ERROR);
        }
        // 生成token
        String tokenData = dbBusiness.getId() + "-" + RoleEnum.BUSINESS.name();
        String token = TokenUtils.createToken(tokenData, dbBusiness.getPassword());
        dbBusiness.setToken(token);
        return dbBusiness;
    }

    /**
     * 修改密码
     */
    public void updatePassword(Account account) {
        Business dbBusiness = businessMapper.selectByUsername(account.getUsername());
        if (ObjectUtil.isNull(dbBusiness)) {
            throw new CustomException(ResultCodeEnum.USER_NOT_EXIST_ERROR);
        }
        if (!account.getPassword().equals(dbBusiness.getPassword())) {
            throw new CustomException(ResultCodeEnum.PARAM_PASSWORD_ERROR);
        }
        dbBusiness.setPassword(account.getNewPassword());
        businessMapper.updateById(dbBusiness);
    }

    public List<Dict> selectBar() {
        // 获取当前用户信息，可能需要根据实际情况进行调整
        Account currentUser = TokenUtils.getCurrentUser();
        // 获取该商家药物及其销量
        List<Medicines> medicinesList = medicinesMapper.selectByBusinessId(currentUser.getId());// 获取所有医生
        // 按预约数量降序排序并取前10
        List<Medicines> topMedicines = medicinesList.stream()
                .sorted(Comparator.comparingInt(Medicines::getCount).reversed()) // 按照预约数量降序排序
                .limit(10) // 取前10名
                .collect(Collectors.toList());

        // 构建返回的数据格式
        List<Dict> dictList = new ArrayList<>();
        for (Medicines medicines : topMedicines) {
            String medicinesName = medicines.getName();
            Integer count = medicines.getCount();

            Dict dict = Dict.create().set("name",medicinesName ).set("value", count);
            dictList.add(dict);
        }

        return dictList;
    }
}
